package com.yu.util;

import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;


import org.apache.commons.math3.util.Pair;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

import com.stonehenge.backend.tools.StaticToolit;
import com.stonehenge.backend.tools.data.GeneratorSID;


public class SMSComponent  {
    private static final Logger logger = LoggerFactory.getLogger(SMSComponent.class);

    //Map<String, StringAndLong> token2vcode = Maps.newConcurrentMap();
    //Map<String, String> phone2token = Maps.newConcurrentMap();
    
    Map<String, MobileToken> localTokenMap = Maps.newConcurrentMap();

    Random rn = new Random();
    
    String APIKEY = "985baa15bbc10b5b6b95bfe8fb8d2a12";
    long TEMPLATEID = 1729136;
//    long TEMPINVITATION = 1794864;
    
    long TEMPINVITATION = 1799538;
    
    long ORDERSERVICEID = 1799538;
    
    int EXPIRE_IN_MINUTE = 10;
    int TIMEOUT_IN_SECOUND = 10000;
    String name = "你好";

    
    private String genRamdomCode() {
        return String.valueOf(rn.nextInt(9000)+1000);
    }
    


    /**
     * 发送验证码，成功为true
     * @param mobile
     * @param code
     * @return
     */
    public boolean sendSMS(String mobile, String code) {
    	if(false)
    		return true; //开启和关闭短信
    	
        if(code==null || mobile==null || mobile.length()!=11){
            return false;
        }
        if (!Toolkit.isMobile(mobile) )
            return false;
        
        String res="";
        try {
            String codeValue = URLEncoder.encode(String.valueOf(code), OS_SMS.ENCODING);
            String tpl_value = "#code#=" + codeValue + /*"&#name#="+name +*/ "&#minute#="+EXPIRE_IN_MINUTE;
            res = (OS_SMS.tplSendSms(APIKEY, TEMPLATEID, tpl_value, mobile,TIMEOUT_IN_SECOUND));
            logger.info("codeValue=" + codeValue +" tpl_value=" + tpl_value + " server response="+ res + " mobile="+ mobile);
        } catch (Exception e2) {
            logger.error("sms Exception:" , e2);
            res="";
        }

        if(StaticToolit.isEmpty(res))
            return false;
        
        JSONObject object = null;
        try{
            object = (JSONObject) JSON.parse(res);
        }catch(JSONException e){
            logger.error("sms JSONException:" , e);
            return false;
        }
        
        int finalCode= 0;
        if(object!=null)    {   //{"result":{"fee":0.055,"sid":4445166406,"count":1},"code":0,"msg":"OK"}       
            Integer codeServ=(Integer) object.get("code");
            if(codeServ!=null)
                finalCode = codeServ;               
        }else{
            return false;
        }
        
        if(finalCode==0)
            return true;
        else 
            return false;
    }

    
    
    public static void main(String[] args)  {
//    	System.out.println(new SMSComponent().sendSMSInvitation("17095011032", "苏州雷克萨斯车友会", "chemeng"));
    	
    }

    //=============================================================================
    /**
     * 做缓存用的
     * @author hzfulingjin
     *
     */
    class MobileToken{
        String mobile;
        String token;
        long time;
        String vcode;
        public String getMobile() {
            return mobile;
        }
        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
        public String getToken() {
            return token;
        }
        public void setToken(String token) {
            this.token = token;
        }
        public long getTime() {
            return time;
        }
        public void setTime(long time) {
            this.time = time;
        }
        public String getVcode() {
            return vcode;
        }
        public void setVcode(String vcode) {
            this.vcode = vcode;
        }
        @Override
        public String toString(){
        	return JSON.toJSONString(this);
        }
        
    }

}
